<template>
    <div style="width: 90%" id="giftActivity">
        <el-form :model="planForm" :rules="planRules" ref="planForm" label-width="150px">
            <el-button @click="goback()" size="mini" type="primary" style="margin-left: 1000px">返回</el-button>
            <el-input v-model="planForm.uuid" type="hidden"></el-input>
            <el-form-item label="问卷名称：" prop="questionnaireName">
                <el-input
                    v-model="planForm.questionnaireName"
                    :disabled="disabledFlag"
                    style="width: 360px"
                    placeholder="问卷名称"
                    maxlength="30"
                    show-word-limit
                ></el-input>
            </el-form-item>

            <el-form-item label="赠品：" prop="planCouponList">
                <div class="giftTable">
                    <el-table
                        :data="planCouponList"
                        @selection-change="planCouponChecked"
                        border
                        style="font-size: 10px; width: 90%"
                        :header-cell-style="{background: '#eef1f6',color: '#606266',}"
                    >
                        <el-table-column
                            prop="giftCode"
                            label="赠品编码"
                            align="center"
                            width="150"
                        ></el-table-column>
                        <el-table-column
                            prop="giftName"
                            label="赠品名称"
                            align="center"
                            width="150"
                        ></el-table-column>
                        <el-table-column
                            prop="giftPic"
                            label="赠品图片"
                            align="center"
                            width="120"
                        >
                            <template slot-scope="scope">
                                <img :src="scope.row.giftPic" v-if="scope.row.giftPic != '' && scope.row.giftPic != null" width="70" height="50" />
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="giftProperty"
                            label="赠品属性"
                            align="center"
                            width="120"
                        >
                            <template slot-scope="scope">
                                <span v-if="scope.row.giftProperty != '1' && scope.row.giftProperty != '2'">-</span>
                                <span v-if="scope.row.giftProperty == '1'">普通赠品</span>
                                <span v-if="scope.row.giftProperty == '2'">特殊赠品</span>
                            </template>
                        </el-table-column>

                        <el-table-column
                            prop="giftDesc"
                            label="赠品描述"
                            align="center"
                            width="150"
                            show-overflow-tooltip
                        ></el-table-column>
                        <el-table-column
                            label="赠送数量"
                            align="center"
                            width="135"
                        >
                            <template slot-scope="scope">
                                <el-input type="number" :min="0" oninput="value=value.replace(/[^0-9]/g,'')" v-model="scope.row.giveCount"
                                    style=" width: 110px; text-align-last: center;"
                                    v-on:blur="giveCountCheck(scope.row, scope.$index)"
                                    :disabled="disabledFlag && disabledFlagone"
                                >
                                    <!-- <template slot="append">
                                        <span slot="append" v-if="scope.row.giftStyle ==1">件</span>
                                        <span slot="append" v-if="scope.row.giftStyle ==2">张</span>
                                        <span slot="append" v-if="scope.row.giftStyle ==3">次</span>
                                        <span slot="append" v-if="scope.row.giftStyle ==4">次</span>
                                        <span slot="append" v-if="scope.row.giftStyle ==5">积分</span>
                                    </template> -->
                                </el-input>
                            </template>
                        </el-table-column>
                        <el-table-column label="有效期类型" align="center" width="150">
                            <template slot-scope="scope">
                                <el-radio-group v-model="scope.row.validDateType" size="small" v-if="!disabledFlag && scope.row.giftStyle != '1' && scope.row.giftStyle != '3' && scope.row.giftStyle != '5'">
                                    <el-radio-button label="1">天数</el-radio-button>
                                    <!-- <el-radio-button label="2">日期</el-radio-button> -->
                                </el-radio-group>
                                <span v-if=" disabledFlag && scope.row.giftStyle != '1' && scope.row.giftStyle != '3' && scope.row.giftStyle != '5' && scope.row.validDateType == '1'">天数</span>
                                <span v-if=" disabledFlag && scope.row.giftStyle != '1' && scope.row.giftStyle != '3' && scope.row.giftStyle != '5' && scope.row.validDateType == '2'">日期</span>
                                <span v-if="scope.row.giftStyle == '1' || scope.row.giftStyle == '3' || scope.row.giftStyle == '5'" >—</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="有效期" align="center" width="270">
                            <template slot-scope="scope">
                                <el-input
                                    v-if="scope.row.giftStyle != '1' && scope.row.giftStyle != '3' && scope.row.giftStyle != '5'"
                                    type="number"
                                    :min="1"
                                    oninput="value=value.replace(/[^0-9]/g,'')"
                                    v-model="scope.row.dayCount"
                                    style="width: 150px; text-align-last: right"
                                    :disabled="disabledFlag && disabledFlagone"
                                >
                                    <template slot="append">天</template>
                                </el-input>
                                <span v-if="scope.row.giftStyle == '1' || scope.row.giftStyle == '3' || scope.row.giftStyle == '5'">—</span>
                            </template>
                        </el-table-column>
                        <el-table-column  prop="status" label="状态" align="center" width="150">
                            <template slot-scope="scope">
                                <span v-if="scope.row.status == '1'">启用</span>
                                <span v-if="scope.row.status == '0'">弃用</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" fixed="right" align="center" width="200px" v-if="!disabledFlag || !disabledFlagone">
                            <template slot-scope="scope">
                                <el-button size="mini" @click="delprice(scope.$index)" type="text">删除赠品</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div style="margin-top: 10px">
                    <el-button type="primary" @click="selectCoupon('planForm')" v-if="!disabledFlag || !disabledFlagone">选择赠品</el-button>
                    <!-- <el-button @click="deleteCoupon('planForm')" v-if="!disabledFlag">删除赠品</el-button> -->
                </div>
            </el-form-item>
            <el-form-item label="发布状态：" prop="publishStatus">
                <el-radio-group v-model="planForm.publishStatus" :disabled="disabledFlag">
                    <el-radio-button label="0">不发布</el-radio-button>
                    <el-radio-button label="1">发布</el-radio-button>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="问卷描述：" prop="remark">
                <el-input
                    type="textarea"
                    v-model="planForm.remark"
                    :disabled="disabledFlag"
                    placeholder="请输入问卷描述"
                    maxlength="300"
                    show-word-limit
                    :autosize="{ minRows: 2 }"
                    style="width: 650px"
                ></el-input>
            </el-form-item>

            <el-form-item label="问卷题目">
                <el-button v-if="!disabledFlag" type="primary" size="mini" @click="addNewShareList('单选题题目（双击编辑）', 0)">+ 添加单选题</el-button>
                <el-button v-if="!disabledFlag" type="primary" size="mini" @click="addNewShareList('多选题题目（双击编辑）', 1)">+ 添加多选题</el-button>
                <el-button v-if="!disabledFlag" type="primary" size="mini" @click="addNewShareList('评分题题目（双击编辑）', 2)">+ 添加评分题</el-button>
            </el-form-item>

            <el-form-item class="wheelList" label="">
                <div class="list">
                    <div class="item" v-for="(item1, index1) in planForm.subjectDTOList" :key="item1.uuid">
                        <div class="childDiv">
                            <img v-if="planForm.subjectDTOList[index1].subjectType < 3 && !disabledFlag"
                                @click="deleteItem(index1, item1.uuid)" class="close" src="../../assets/img/foodsMan/cancel.png" alt/>
                            <label for="project_type" style="margin-top: 10px; float: left">题目{{ toChinese(index1 + 1) }}：</label>
                            <!-- <el-form-item label="题目一" class="title"  prop="title"  :required="true">  -->
                            <span v-show="!item1.setNo && planForm.subjectDTOList[index1].subjectName.trim() != ''" @dblclick="changeNo(item1.uuid)" style="padding: 10px" >{{ item1.subjectName }}</span>
                            <el-input
                                v-show="item1.setNo || planForm.subjectDTOList[index1].subjectName.trim() == ''"
                                @blur="unfocused(item1.uuid, $event)"
                                :disabled="disabledFlag"
                                v-model="planForm.subjectDTOList[index1].subjectName"
                                size="mini"
                                class="input_edit"
                                :placeholder="planForm.subjectDTOList[index1].placeholderTitle"
                                clearable
                                maxlength="50"
                                show-word-limit
                            ></el-input>
                            <el-button v-if="planForm.subjectDTOList[index1].subjectType < 2 && !disabledFlag" icon="el-icon-circle-plus-outline" type="text"
                            style="margin-left: 10px"  @click=" handlerAddOpt(planForm.subjectDTOList[index1], index1)">答案选项</el-button>
                        </div>
                        <div class="content">
                            <el-row :span="24">
                                <el-col :span="22" v-for="(option, index2) in planForm.subjectDTOList[index1].optionDTOS" :key="option.uuid" class="el-trave">
                                    <!-- <el-col :span="2"><img class="danxuan" src="../../assets/img/icon/danxuan.png" alt/></el-col>
                            <el-col :span="2"><img class="danxuan" src="../../assets/img/icon/check_box.png" alt/></el-col>
                             :rules="[{required: true, message: '选项内容不能为空', trigger: 'blur'}]"
                             -->
                                    <el-col :span="20" v-show="planForm.subjectDTOList[index1].subjectType != 2">
                                        <el-form-item  class="redItem" :prop="'subjectDTOList.' +index1 +'.optionDTOS.' +index2 +'.optionName'" :rules="[{required: true,message: '选项内容不能为空',trigger: 'blur', },]" size="mini">
                                            <span slot="label">
                                                <span class="span-box">
                                                  <img v-if="planForm.subjectDTOList[index1].subjectType == 0" src="../../assets/img/icon/danxuan.png" class="check"/>
                                                  <img v-if="planForm.subjectDTOList[index1].subjectType == 1" src="../../assets/img/icon/check_box.png" class="check"/>
                                                    <!-- <i v-if="planForm.subjectDTOList[index1].subjectType == 0" class="el-icon-chat-round ico-pre"></i>
                                                    <i v-if="planForm.subjectDTOList[index1].subjectType == 1" class="el-icon-chat-square ico-pre"></i> -->
                                                    <span>选项{{toChinese(index2 + 1)}}</span></span>
                                            </span>
                                            <el-input :disabled="disabledFlag" v-model="planForm.subjectDTOList[index1].optionDTOS[index2].optionName" placeholder="请输入答案选项内容"clearable></el-input>
                                        </el-form-item>
                                    </el-col>

                                    <el-col :span="2" v-show="planForm.subjectDTOList[index1].subjectType != 2">
                                        <i class="el-icon-remove-outline" v-if="!disabledFlag" @click="handlerRemove(planForm.subjectDTOList[index1].optionDTOS,option)"></i>
                                    </el-col>
                                </el-col>

                                <el-col :span="2">
                                    <div class="upDownWrapper">
                                        <el-button icon="el-icon-arrow-up" style="border-radius: 30px" @click="upClickItem(index1,planForm.subjectDTOList)"
                                        v-if="index1 !== 0 && planForm.subjectDTOList[index1].subjectType < 3 && !disabledFlag" circle></el-button>
                                        <el-button icon="el-icon-arrow-down" @click="downClickItem( index1, planForm.subjectDTOList)"
                                        v-if="index1 !== planForm.subjectDTOList.length - 2 && planForm.subjectDTOList[index1].subjectType < 3 && !disabledFlag" circle></el-button>
                                    </div>
                                </el-col>
                            </el-row>
                        </div>
                    </div>
                </div>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="openDialogVisibleLeve">跳题设置</el-button>
            </el-form-item>

            <el-form-item>
                <el-button  type="primary" @click="submitForm('planForm')" v-if="!disabledFlag || !disabledFlagone">保 存</el-button>
                <el-button @click="resetForm('planForm')" v-if="!disabledFlag">取 消</el-button>
                <el-button @click="resetForm('planForm')" v-if="disabledFlag">返 回</el-button>
            </el-form-item>
        </el-form>

        <el-dialog title="选择赠品" :visible.sync="dialogVisibleCoupon" width="55%">
            <el-form  :inline="true" :model="formCoupon" class="search-form-inline" style="margin-top: -20px">
                <el-form-item label="赠品编码：">
                    <el-input v-model="formCoupon.giftCode" clearable placeholder style="width: 200px"></el-input>
                </el-form-item>
                <el-form-item label="赠品名称：">
                    <el-input  v-model="formCoupon.giftName" clearable placeholder style="width: 200px"></el-input>
                </el-form-item>
                <el-button type="primary" size="mini" icon="el-icon-search" @click="getCouponList()">查询</el-button>
            </el-form>
            <el-table
                ref="singleTable"
                :data="couponList"
                @selection-change="couponChecked"
                @row-click="handleRowClick"
                border
                style="font-size: 10px; width: 100%"
                :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
            >
                <el-table-column type="selection"  width="60"  align="center" fixed disabled></el-table-column>
                <el-table-column  prop="giftPic" label="赠品图片" align="center" width="120">
                    <template slot-scope="scope">
                        <img :src="scope.row.giftPic" v-if="scope.row.giftPic != '' && scope.row.giftPic != null " width="70" height="50"/>
                    </template>
                </el-table-column>
                <el-table-column prop="giftType" label="赠品类型"  align="center" width="120">
                    <template slot-scope="scope">
                        <span v-if="scope.row.giftType == '1'">实物赠品</span>
                        <span v-if="scope.row.giftType == '2'">虚拟赠品</span>
                        <span v-if="scope.row.giftType == '3'">虚拟赠品</span>
                    </template>
                </el-table-column>
                <el-table-column  prop="giftProperty"  label="赠品属性" align="center" width="120">
                    <template slot-scope="scope">
                        <span  v-if="scope.row.giftProperty != '1' &&scope.row.giftProperty != '2'">-</span>
                        <span v-if="scope.row.giftProperty == '1'">普通赠品</span>
                        <span v-if="scope.row.giftProperty == '2'">特殊赠品</span>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="giftCode"
                    label="赠品编码"
                    align="center"
                    width="150"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    prop="giftName"
                    label="赠品名称"
                    align="center"
                    width="200"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    prop="giftDesc"
                    label="赠品描述"
                    align="center"
                    show-overflow-tooltip
                ></el-table-column>
            </el-table>
            <div class="block" style="margin-top: 22px; overflow: hidden">
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :page-sizes="[5, 10, 20, 30, 50, 100]"
                    :current-page="listQuery.current"
                    :page-size="listQuery.size"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total3"
                ></el-pagination>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisibleCoupon = false">取 消</el-button>
                <el-button type="primary" @click="couponConfirm()">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog
            title="设置跳题规则"
            :visible.sync="dialogVisibleLevel"
            width="75%"
            center
        >
            <el-table
                :data="planForm.subjectDTOList"
                border
                style="font-size: 10px; width: 100%"
                height="400"
                :show-header="false"
                :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
                :row-class-name="tableRowClassName"
                class="el-table"
            >
                <el-table-column prop="subjectName" label="题目内容"  min-width="35%" header-align="center">
                    <template slot-scope="scope">
                        <span >题目{{toChinese(scope.$index + 1) + ":" + scope.row.subjectName }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="" align="center">
                    <template slot-scope="scope1">
                        <el-table
                            :data="scope1.row.optionDTOS"
                            :show-header="false"
                            border
                            style="width: 100%"
                        >
                            <el-table-column prop="optionName" label=""min-width="45%">
                                <template slot-scope="scope">
                                    <span v-if="scope1.row.subjectType != 2">选项{{toChinese(scope.$index + 1) +":" + scope.row.optionName }}</span>
                                    <span v-if="scope1.row.subjectType == 2">{{scope.row.optionName}}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="jumpSubjectId" label="" min-width="55%">
                                <template slot-scope="scope">
                                    <el-select
                                        :disabled="disabledFlag && disabledFlagone"
                                        v-model="scope.row.jumpSubjectId"
                                        @change="jumpChange(scope.row)"
                                        placeholder="不跳转,按顺序答题"
                                        style="width: 100%"
                                    >
                                        <el-option label="不跳转,按顺序答题" value=""></el-option>
                                        <el-option v-for="(item,indexS) in planForm.subjectDTOList" :key="item.uuid" :label="'题目' + toChinese(indexS + 1) +':' +item.subjectName"
                                            :value="item.uuid" v-show="scope1.$index < indexS"></el-option>
                                    </el-select>
                                    <el-input v-model="scope.row.jumpType" type="hidden"></el-input>
                                </template>
                            </el-table-column>
                        </el-table>
                    </template>
                </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
                <el-button v-if="!disabledFlag || !disabledFlagone" @click="dialogVisibleLevel = false">取 消</el-button>
                <el-button v-if="!disabledFlag || !disabledFlagone" type="primary" @click="dialogVisibleLevel = false">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import { v4 as uuidv4 } from 'uuid';
import qs from "qs";
import {queryChooseGiftsList, addQuestionnaire, qryQuestionnaireInfo} from "@/api/questionnaireEdit";
export default {
  data() {
    return {
      oldValue: false,
      dialogVisibleLevel: false,
      loading: true,
      lsPlanCouponList: [],
      lsCouponList: [],
      planCouponList: [],
      couponList: [],
      planForm: {
        uuid: uuidv4(),
        questionnaireName: "",
        remark: "",
        subjectDTOList: [],
        status: "0",
        giftDTOList: [],
        publishStatus:"0",
      },
      formCoupon: {
        couponName: "",
        giftCode:"",
        giftName:"",
        giftType:""
      },
      dialogVisibleCoupon: false,
      disabledFlag: false,
      disabledFlagone: true,
      listQuery: {
        current: 1,
        size: 10
      },
      total3:0,
      total: 0,
            pickerOptions: {
      },
      planRules: {
       questionnaireName: [{ required: true, message: "问卷名称", trigger: "blur" }],
       publishStatus:[{ required: true, message: "请选择发布状态", trigger: "blur" }],
        giftName: [{ required: true, message: "请输入赠品名称", trigger: "blur" }],
        remark: [{ required: true, message: "请输入问卷描述", trigger: "blur" }],
        planCouponList: [{ required: true,type: 'array', message: "请选择赠品", trigger: "change",
        validator: function (value) { return value.length !== 0}}],
      }
    };
  },
  components: {},
  computed: {},
  mounted() {
    this.disabledFlag=this.$route.params.disabledFlag
    this.disabledFlagone=this.$route.params.disabledFlagone
    var v = this.$route.params.edit;
    if (v) {
      // 修改，回显值
      this.planForm.uuid = v.uuid;
      this.planForm.questionnaireName = v.questionnaireName;
      this.planForm.remark = v.remark;
      this.planForm.status = v.status !=1 ? 0 : v.status;
      this.qryQuestionnaireInfo(v.uuid);

    } else {
      // 新增，默认值
      this.planForm.status = "0";
      this.planForm.subjectDTOList.push({uuid: uuidv4(),
           questionnaireId: this.planForm.uuid,
           subjectNum: 99,
           setNo:"",
           subjectName: "用户反馈（双击编辑）",
           subjectType: 3, //题目类型(0-单选题1-多选题2-评分题3-用户反馈)
           optionDTOS: []});

      this.getCouponList();
    }
  },
  methods: {
    changeNo: function (id) {
    this.planForm.subjectDTOList.forEach(item => {
      if(item.uuid == id)
      {this.$set(item,"setNo",true);this.oldValue = item.subjectName}
      else { item.setNo = false}
    })
    },
    unfocused: function (id,e) {
    this.planForm.subjectDTOList.forEach(item => {if(item.uuid == id) {this.$set(item,"setNo",false);} })
    // if(this.oldValue != e.target.value) {this.changeNo(id) }
    },
    toChinese(val){
    let chin_list=['一','二','三','四','五','六','七','八','九','十'];//所有的数值对应的汉字
    let sn = parseInt(val);//这里由于我的后台是从0开始排序
    if(sn<=10){
      return chin_list[sn-1];
    }
    else if(sn<=100){
      if(sn<20)
        return '十'+chin_list[sn%10-1];
      if(sn%10==0)
        return chin_list[Math.floor(sn/10)-1]+'十';
      else
        return chin_list[Math.floor(sn/10)-1]+'十'+chin_list[sn%10-1];
    }
    else{
      //可以支持更多
    }
},
    giveCountCheck(row, index) {
      let val = row.giveCount;
      if (val === null || val === undefined || val === "") {
        this.$message({showClose: true, message: "填入数量不能为空",type: "warning"});
        val = 1;
      } else if (isNaN(val)){
        this.$message({showClose: true, message: "填入数量格式错误",type: "warning"});
        val = 1;
      } else if (val < 1){
        this.$message({showClose: true, message: "填入数量应大于0",type: "warning"});
        val = 1;
      }
       this.planCouponList[index].giveCount = parseInt(val);
      return true;
    },
         delprice(index) {
      this.planCouponList.splice(index, 1);
    },
    goback() {
      this.$router.go("-1");
    },
    qryQuestionnaireInfo(uuid) {
      let data = {uuid:uuid};
      qryQuestionnaireInfo(data).then(res => {
        this.planForm = res.result;
        this.planForm.subjectDTOList.forEach(e => this.$set(e,"setNo",false));
        this.$set(this.planForm,"publishStatus",String(this.planForm.status != 1 ? 0 : this.planForm.status));
        this.planCouponList = res.result.giftDTOList;
        this.getCouponList();
      });
      this.loading = false;
    },

    getCouponList() {
      let data = {
        current: this.listQuery.current,
        size: this.listQuery.size,
        condition: {
          status: 1,
      activityType:3,
          giftName: this.formCoupon.giftName.trim(),
          giftCode: this.formCoupon.giftCode.trim(),
          giftType: this.formCoupon.giftType
        },
        ascs: [],
        descs: []
      };
      queryChooseGiftsList(data).then(res => {
        this.couponList = res.records;
        this.total3=res.total-this.planCouponList.length;
        // 去掉已选的
        for (var i in this.planCouponList) {
          this.removeByValue(this.couponList,"uuid",this.planCouponList[i].giftId);
        }
      });
      this.loading = false;
    },

    planCouponChecked(row) {
      this.lsPlanCouponList = row;
    },
    couponChecked(row) {
      this.lsCouponList = row;
      if (this.lsCouponList.length > 1) {
          this.$refs.singleTable.toggleRowSelection(this.lsCouponList[0]);
          }
    },
    // 点击行触发，选中或不选中复选框
    handleRowClick(row, column, event) {
      this.$refs.singleTable.toggleRowSelection(row)
    },
       handleSizeChange(val) {
      this.listQuery.size = val;
      this.getCouponList();
    },
    handleCurrentChange(val) {
      this.listQuery.current = val;
      this.getCouponList();
    },
    selectCoupon() {
      // 显示选择卡券对话框
      this.dialogVisibleCoupon = !this.dialogVisibleCoupon;
      this.getCouponList();
    },
    deleteCoupon() {
      // 删除已选择的卡券
      this.couponList = this.couponList.concat(this.lsPlanCouponList);
      for (var i in this.lsPlanCouponList) {
        this.removeByValue(
          this.planCouponList,
          "uuid",
          this.lsPlanCouponList[i].uuid
        );
      }
    },
    couponConfirm() {
      this.dialogVisibleCoupon = !this.dialogVisibleCoupon;
      for (var i in this.lsCouponList) {
        this.$set(this.lsCouponList[i],"giveCount",1);
        this.$set(this.lsCouponList[i],"isLimitQuantity",0);
        this.$set(this.lsCouponList[i],"validDateType",1);
        this.$set(this.lsCouponList[i],"giftCount",1000);
      }
      if(this.lsCouponList.length == 1) this.planCouponList = this.lsCouponList;
     for (var i in this.planCouponList) {
     if (
          this.planCouponList[i].giftId == null ||
          this.planCouponList[i].giftId == undefined
        ) {
          this.planCouponList[i].giftId = this.planCouponList[i].uuid;
          this.planCouponList[i].uuid=null
        }
     }
    },

    submitForm(formName) {
      // 保存奖品
      if (this.planForm.questionnaireName == "" || this.planForm.questionnaireName == null) {
        this.$message.error("请输入问卷名称");
        return;
       }
         if ( this.planCouponList.length == 0) {
        this.$message.error("请选择赠品");
        return;
      }
       this.planForm.status = this.planForm.publishStatus;
       if (this.planForm.remark == "" || this.planForm.remark == null) {
        this.$message.error("请输入问卷描述");
        return;
       }

       let r = new RegExp("^[1-9][0-9]*$");
      for (var ii in this.planCouponList) {
        var flag3 = true;
        let giftStyle = this.planCouponList[ii].giftStyle;
        let validDateType = this.planCouponList[ii].validDateType;
        let dayCount = this.planCouponList[ii].dayCount;

        if(giftStyle != '1' && giftStyle != '3' && giftStyle != '5'){
        if (dayCount == null || dayCount == "" || !r.test(dayCount)) {
          flag3 = false;
          break;
        }
        }
      }
      if (!flag3) {
        this.$message({ message: "请正确输入有效天数,且不能为空", type: "warning" }); return;
      }



      for (var i in this.planCouponList) {
        // 删除提交时不需要的属性或容易导致错误的属性

        delete this.planCouponList[i].createTime;
        delete this.planCouponList[i].createUser;
        delete this.planCouponList[i].updateTime;
        delete this.planCouponList[i].updateUser;
        delete this.planCouponList[i].comments;
        delete this.planCouponList[i].validCreateDate;
        delete this.planCouponList[i].validEndDate;
      }
      this.planForm.giftDTOList = this.planCouponList;
      let flag = false;
      this.planForm.subjectDTOList.forEach((item, i) => {
        if(item.subjectType == 2) {flag = true}
        item.subjectNum = i;
        item.optionDTOS.forEach((item, j) => {item.optionNum = j;});
      });
      if (!flag) {
        this.$message({ message: "至少添加一个评分题", type: "warning" }); return;
      }

      if(!this.disabledFlag){
      addQuestionnaire(this.planForm).then(res => {
        if (res.code == "1") {
          this.$message({
            showClose: true,
            message: "保存成功",
            type: "success"
          });
        this.$router.push("questionnaireList");
        } else {
          this.$message({
            showClose: true,
            message: res.message,
            type: "error"
          });
        }
      });
      } else {
        addQuestionnaire(this.planForm).then(res => {
        if (res.code == "1") {
          this.$message({
            showClose: true,
            message: "修改成功",
            type: "success"
          });
        this.$router.push("questionnaireList");
        } else {
          this.$message({
            showClose: true,
            message: res.message,
            type: "error"
          });
        }
      });
      }
    },
    // 数组，属性，属性值
    removeByValue: function(arr, attr, value) {
      if (arr == null) {
        return;
      }
      var index = 0;
      for (var i in arr) {
        if (arr[i][attr] == value) {
          index = i;
          break;
        }
      }
      arr.splice(index, 1);
    },
    handleRemove(file, fileList) {
      let newfileList = [];
      fileList.forEach((item, i) => {
        let data = {
          name: item.name,
          url: item.url
        };
        newfileList.push(data);
      });
      this.fileList = newfileList;
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.$router.push("questionnaireList");
    },
    five_star_option(q,v) {
      return [
        {uuid: uuidv4(),questionnaireId: q,subjectId: v,optionNum: 1,optionName: "一颗星",jumpType: 0,jumpSubjectId: "" },
        {uuid: uuidv4(),questionnaireId: q,subjectId: v,optionNum: 2,optionName: "二颗星",jumpType: 0,jumpSubjectId: "" },
        {uuid: uuidv4(),questionnaireId: q,subjectId: v,optionNum: 3,optionName: "三颗星",jumpType: 0,jumpSubjectId: "" },
        {uuid: uuidv4(),questionnaireId: q,subjectId: v,optionNum: 4,optionName: "四颗星",jumpType: 0,jumpSubjectId: "" },
        {uuid: uuidv4(),questionnaireId: q,subjectId: v,optionNum: 5,optionName: "五颗星",jumpType: 0,jumpSubjectId: "" }
      ]
    },
    three_option(q,v) {
      return [
        {uuid: uuidv4(),questionnaireId: q,subjectId: v,optionNum: 1,optionName: "答案选项一",jumpType: 0,jumpSubjectId: "" },
        {uuid: uuidv4(),questionnaireId: q,subjectId: v,optionNum: 2,optionName: "答案选项二",jumpType: 0,jumpSubjectId: "" },
        {uuid: uuidv4(),questionnaireId: q,subjectId: v,optionNum: 3,optionName: "答案选项三",jumpType: 0,jumpSubjectId: "" }
      ]
    },
    //新增单选题目
    addNewShareList(title,type) {
      let subjectId = uuidv4();
      this.planForm.subjectDTOList.splice(-1,0,{uuid: subjectId,
           questionnaireId: this.planForm.uuid,
           subjectNum: this.planForm.subjectDTOList.length+1,
           subjectName: title,setNo:"",
           subjectType: type, //题目类型(0-单选题1-多选题2-评分题3-用户反馈)
           optionDTOS: type < 2 ? this.three_option(this.planForm.uuid,subjectId) : (type == 2 ? this.five_star_option(this.planForm.uuid,subjectId) : [] ),
           placeholderTitle:title});
    },
    deleteItem(index,uuid) {

      //删除题目项;
      this.$confirm("此操作将永久删除该配置, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          this.planForm.subjectDTOList.splice(index, 1);
          this.planForm.subjectDTOList.forEach((item, j) => {
          item.optionDTOS.forEach((it, i) => {
          if(it.jumpSubjectId == uuid ) {
               it.jumpType = 0
               it.jumpSubjectId = ""
               }
            })
                });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //新增答案选项
    handlerAddOpt(array1,index) {
    let length = array1.optionDTOS.length+1
    let array = JSON.parse(JSON.stringify(this.planForm.subjectDTOList[index].optionDTOS));
      array.push({uuid: uuidv4(),
          questionnaireId: array1.questionnaireId,
          subjectId: array1.uuid,
          optionNum: length,
          optionName: "答案选项"+this.toChinese(length),
          jumpType: 0, //是否跳转(0-否1-是)
          jumpSubjectId: "" });
      this.planForm.subjectDTOList[index].optionDTOS = JSON.parse(JSON.stringify(array));
    },
    //删除答案选项
    handlerRemove(list,item) {
      var index = list.indexOf(item)
      if (index !== -1) {
        list.splice(index, 1)
      }
    },
    //隐藏行
    tableRowClassName: function (row, index) {
        if (row.row.subjectType == 1 || row.row.subjectType == 3) {
          return 'hidden-row';
        }
        return '';
      },
    jumpChange(row) {
      if (row.jumpSubjectId != "" ) {
        row.jumpType = 1;
      } else {
        row.jumpType = 0;
      }
    },


    // 上移
    upClickItem(index,list) {
      let newArr = this.swaps(list, index, index - 1)
      list = newArr
    },
    // 下移
    downClickItem(index,list) {
      let newArr = this.swaps(list, index, index + 1)
      list = newArr
    },
    // 上下移动的核心。
    swaps(pageData, index1, index2) {
      let index = this.planForm.subjectDTOList.findIndex((item, i) => {
        item.optionDTOS.forEach((item, j) => {return item.subjectType == 1});
      });
      if(index > -1) {
      this.$confirm("此操作将恢复跳题规则为默认状态，是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.planForm.subjectDTOList.forEach((item, i) => {
        item.optionDTOS.forEach((item, j) => {item.jumpSubjectId = "";item.jumpType = 0;});
      });
          pageData[index1] = pageData.splice(index2, 1, pageData[index1])[0];
          return pageData;
        })
        .catch(() => {
        });
      } else {
          pageData[index1] = pageData.splice(index2, 1, pageData[index1])[0];
          return pageData;
      }
    },

    openDialogVisibleLeve() {
      let index = this.planForm.subjectDTOList.findIndex((item, i) => {
        return item.subjectName == ''
      });
      if(index > -1) {
        let num = index+1
        this.$message.warning("题目"+this.toChinese(num) +";标题不能为空！");
        return
      }
      this.dialogVisibleLevel = true
    },


  },
};
</script>
<style lang="less" scoped>
.el-col-20 {
    // border: 1px solid #ebeef5;
    // margin-left: 150px;
    // width: 60%;
}
.el-input {
    width: 60%;
}
.search-form-inline {
    border: 1px solid #ebeef5;
    line-height: 30px;
    padding: 12px;
    margin-bottom: 5px;
}
thead {
    .el-table-column--selection {
        .cell {
            display: none;
        }
    }
}
#giftActivity
    .giftTable
    table
    .el-radio-button-inner-child
    .el-radio-button__inner {
    padding: 0;
}
#giftActivity .giftTable table .el-radio-button-inner-child .el-input__inner {
    border: none;
    height: 30px;
}

.wheelList .list {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
}
.wheelList .item {
    width: 840px;
    border: 1px solid #f2f2f2;
    border-radius: 5px;
    display: flex;
    flex-direction: column;
    align-items: left;
    padding: 20px;
    box-sizing: border-box;
    background: #ffffff;
    position: relative;
    margin: 10px;
}
.wheelList .item .childDiv {
    height: 36px;
    margin-bottom: 10px;
}
.wheelList .item .content {
    margin-left: 20px;
    flex: 1;
}
.close {
    width: 30px;
    height: 30px;
    padding: 10px;
    box-sizing: border-box;
    position: absolute;
    top: 10px;
    right: 10px;
    z-index: 11;
}
.check {
    width: 30px;
    height: 30px;
    padding: 10px;
    box-sizing: border-box;
    position: relative;
    top: 10px;
    left: 5px;
    z-index: 11;
}
.danxuan {
    width: 20px;
    height: 20px;
    padding: 10px;
    box-sizing: border-box;
    position: absolute;
    top: 10px;
    left: 10px;
    z-index: 11;
}
.title {
    text-align: left !important;
}
.upDownWrapper {
    width: 100px;
    height: 20px;
    border-radius: 5px;
    // border: 1px solid #f2f2f2;
    position: relative;
    // background: #ffffff;
    margin-left: 20px;
}
.upDownWrapper .el-button + .el-button {
    margin-left: 0px;
    margin-right: 10px;
}
</style>
<style>
.el-table .hidden-row {
    display: none;
}
.redItem .el-form-item__label {
    width: 1 !important;
    margin-top: -10px;
}
</style>
<style scoped>
.span-box {
    display: inline-block;
    position: relative;
}
.ico-pre {
    position: absolute;
    left: -21px;
    top: 12px;
}
</style>
